import React, { useState, useEffect } from 'react';
import { Table, Input, Button, Space, Tooltip, Card } from 'antd';
import { SearchOutlined, ReloadOutlined, SettingOutlined } from '@ant-design/icons';
import type { TableProps, TablePaginationConfig } from 'antd/es/table';
import type { FilterValue, SorterResult } from 'antd/es/table/interface';
import CONFIG from '../../config';
import './style.less';

const { Search } = Input;

export interface StandardTableProps<T> extends Omit<TableProps<T>, 'pagination' | 'title'> {
  title?: string;
  loading?: boolean;
  data: {
    list: T[];
    pagination?: {
      total: number;
      current: number;
      pageSize: number;
    };
  };
  searchPlaceholder?: string;
  showSearch?: boolean;
  showReload?: boolean;
  showSetting?: boolean;
  onSearch?: (value: string) => void;
  onReload?: () => void;
  onSettingClick?: () => void;
  onTableChange?: (
    pagination: TablePaginationConfig,
    filters: Record<string, FilterValue | null>,
    sorter: SorterResult<T> | SorterResult<T>[]
  ) => void;
  toolBarRender?: () => React.ReactNode[];
}

function StandardTable<T extends Record<string, any>>({
  title,
  loading = false,
  data,
  searchPlaceholder = '搜索',
  showSearch = true,
  showReload = true,
  showSetting = false,
  onSearch,
  onReload,
  onSettingClick,
  onTableChange,
  toolBarRender,
  ...restProps
}: StandardTableProps<T>) {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  // 重置选中行
  useEffect(() => {
    setSelectedRowKeys([]);
  }, [data.list]);

  // 处理表格变化
  const handleTableChange = (
    pagination: TablePaginationConfig,
    filters: Record<string, FilterValue | null>,
    sorter: SorterResult<T> | SorterResult<T>[]
  ) => {
    if (onTableChange) {
      onTableChange(pagination, filters, sorter);
    }
  };

  // 处理搜索
  const handleSearch = (value: string) => {
    if (onSearch) {
      onSearch(value);
    }
  };

  // 处理刷新
  const handleReload = () => {
    if (onReload) {
      onReload();
    }
  };

  // 处理设置点击
  const handleSettingClick = () => {
    if (onSettingClick) {
      onSettingClick();
    }
  };

  // 处理行选择变化
  const handleRowSelectionChange = (selectedKeys: React.Key[]) => {
    setSelectedRowKeys(selectedKeys);
  };

  // 构建表格工具栏
  const renderToolbar = () => {
    const customTools = toolBarRender ? toolBarRender() : [];

    return (
      <div className="standard-table-toolbar">
        <div className="standard-table-toolbar-left">
          {showSearch && (
            <Search
              placeholder={searchPlaceholder}
              onSearch={handleSearch}
              style={{ width: 240 }}
              allowClear
            />
          )}
        </div>
        <div className="standard-table-toolbar-right">
          <Space>
            {customTools}
            {showReload && (
              <Tooltip title="刷新">
                <Button icon={<ReloadOutlined />} onClick={handleReload} />
              </Tooltip>
            )}
            {showSetting && (
              <Tooltip title="列设置">
                <Button icon={<SettingOutlined />} onClick={handleSettingClick} />
              </Tooltip>
            )}
          </Space>
        </div>
      </div>
    );
  };

  // 构建分页配置
  const paginationProps: TablePaginationConfig | false = data.pagination
    ? {
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: (total) => `共 ${total} 条记录`,
        ...CONFIG.pagination,
        ...data.pagination,
      }
    : false;

  return (
    <Card
      title={title}
      bordered={false}
      className="standard-table-card"
      bodyStyle={{ padding: 0 }}
    >
      {renderToolbar()}
      <Table<T>
        rowKey="id"
        loading={loading}
        dataSource={data.list}
        pagination={paginationProps}
        onChange={handleTableChange}
        {...restProps}
        rowSelection={
          restProps.rowSelection
            ? {
                ...restProps.rowSelection,
                selectedRowKeys,
                onChange: handleRowSelectionChange,
              }
            : undefined
        }
      />
    </Card>
  );
}

export default StandardTable;